<?php

	// No direct access to this file
	defined('_JEXEC') or die('Restricted access');
	require_once(JPATH_COMPONENT_SITE . '/helpers/LanguageHelper.php');


	/**
	 * Created by JetBrains PhpStorm.
	 * User: martin.maliska
	 * Date: 24.2.2012
	 * Time: 22:18
	 * To change this template use File | Settings | File Templates.
	 */
	class ShopRenderer {

		private $languageCount;
		private $currentLangIndex;
		private $header;

		public function render(ShopDao $shopDao) {
			$languages = LanguageHelper::getLanguages();
			$this->languageCount = count($languages);
			$this->currentLangIndex = LanguageHelper::getLanguageIndex($languages);

			$this->startPage();
			$table = $shopDao->loadShopItems();
			$config = $shopDao->loadTableConfig();
			$sliders = array();
			$previousTableIndex = 1;
			foreach ($table as $row) {
				$data = explode("|", $row->row_data);
				if ($row->table_id > 1) {
					if ($row->row_id == 0) {
						if ($row->table_id > 2) {
							$this->endTable($previousTableIndex);
						}
						$this->startTable($config[$row->table_id]->picture, $this->prepareTableHeader($data));
					} else {
						$this->renderRow($this->projectDataForLanguage($data), $row->table_id, $row->row_id, $sliders);
					}
					$previousTableIndex = $row->table_id;
				} else {
					if (($this->currentLangIndex - 1) == $row->row_id) {
						$this->header = $data;
					}
				}
			}
			if (sizeof($table) > 0) $this->endTable($previousTableIndex);
			$this->endPage($sliders, sizeof($table) > 0);
		}

		private function projectDataForLanguage($data) {
			$projectedData = array();
			array_push($projectedData, $data[$this->currentLangIndex - 1]);
			array_push($projectedData, $data[$this->languageCount]);
			array_push($projectedData, $data[$this->languageCount +1]);
			array_push($projectedData, $data[$this->languageCount +2]);
			array_push($projectedData, $data[$this->languageCount +3]);
			if (array_key_exists($this->languageCount +4 + $this->currentLangIndex -1, $data)) {
				array_push($projectedData, $data[$this->languageCount +4 + $this->currentLangIndex -1]);
			}
			return $projectedData;
		}

		/**
		 * @param $data
		 * @return array
		 */
		public function prepareTableHeader($data) {
			$tableName = $data[$this->currentLangIndex -1];
			return array_merge(array($tableName), $this->header);
		}

		private function startTable($tableImage, $tableHeader) {
			require("shop_table_header.php");
		}

		private function renderRow($data, $tableIndex, $rowIndex, &$sliders) {
			require("shop_table_row.php");
		}

		private function endTable($tableIndex) {
			require("shop_table_footer.php");
		}

		private function startPage() {
			require("shop_page_header.php");
		}

		private function endPage(&$sliders, $submitEnabled) {
			require("shop_page_footer.php");
		}

	}
